<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div>

    用户名:<input type="text" name="username" id="userName"><br>
    密码:<input type="text" name="password" id="pwd"><br>
    性别:
    <input type="radio" name="sex" value="0">男
    <input type="radio" name="sex" value="1">女
    <input type="radio" name="sex" value="2">保密
    <br>
    身份：
    <select name="identity" id="sl-identity">
        <option value="0">学生</option>
        <option value="1">老师</option>
        <option value="2">管理员</option>
    </select>
    <br>
    爱好：
    <input type="checkbox" name="hobby" value="0">看书
    <input type="checkbox" name="hobby" value="1">唱歌
    <input type="checkbox" name="hobby" value="2">跳舞
    <br>

    <button id="btn-register">注册</button>



</div>

</body>
</html>
<script src="./js/axios.min.js"></script>
<script>

    // 注册按钮点击事件

    document.getElementById('btn-register')
    .onclick = function () {

        const userName = document.getElementById('userName').value
        const pwd = document.getElementById('pwd').value
        const identity = document.getElementById('sl-identity').value

        //获取单选按钮的值
        const sex = document.querySelector('input[name="sex"]:checked').value

        //获取复选框的值
        const hobby = []
        // document.querySelectorAll('input[name="hobby"]:checked').forEach(function (item) {
        //     hobby.push(item.value)
        // })

        for (let i = 0;i < document.getElementsByName('hobby').length;i++){
            if (document.getElementsByName('hobby')[i].checked){
                hobby.push(document.getElementsByName('hobby')[i].value)
            }

        }

        const url = '/user/register'
        const data = {
            "username":userName,
            "password":pwd,
            sex,
            identity,
            hobby
        }
        axios.post(url,data)
            .then(res => {
                // console.log(res.data)
                const R = res.data

                if (R.code === 200){
                    alert('注册成功')
                    // 跳转到首页
                    //保存数据到本地浏览器
                    localStorage.setItem('user',JSON.stringify(R.data))
                    location.href = '/index.html'
                }else {
                    alert(R.msg)
                }
            });






    }



</script>

